﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ninject.Core;
using System.Web.Routing;
using Wicresoft.SMS.Data;
using System.Globalization;

namespace Wicresoft.SMS.Web
{
    public class CustomControllerFactory : DefaultControllerFactory
    {
        private class FacotryBindingTable : StandardModule
        {
            public override void Load()
            {
                Bind<IUserRoleService>()
                    .To<UserRoleService>()
                    .WithConstructorArgument("provider", DependencyInjectFacotry.CreateConnectStringProvider());
                Bind<ICommonService>()
                    .To<sqlCommonService>()
                    .WithConstructorArgument("provider", DependencyInjectFacotry.CreateConnectStringProvider());
            }
        }

        private IKernel kernel = new StandardKernel(new FacotryBindingTable());

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null){
                throw new HttpException(404,
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "The controller for path '{0}' was not found or does not implement IController.",
                        requestContext.HttpContext.Request.Path));
            }
            if (!typeof(IController).IsAssignableFrom(controllerType))
            {
                throw new ArgumentException(
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "The controller type '{0}' must implement IController.",
                        controllerType),
                    "controllerType");
            }
            try{
                return (IController)kernel.Get(controllerType);
            }
            catch (Exception ex){
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "An error occurred when trying to create a controller of type '{0}'. Make sure that the controller has a parameterless public constructor.",
                        controllerType),
                    ex);
            }
        }
    }
}